/*
 * Unidata Platform
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 *
 * Commercial License
 * This version of Unidata Platform is licensed commercially and is the appropriate option for the vast majority of use cases.
 *
 * Please see the Unidata Licensing page at: https://unidata-platform.com/license/
 * For clarification or additional options, please contact: info@unidata-platform.com
 * -------
 * Disclaimer:
 * -------
 * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
 * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
 * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
 * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
 * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
 */
package org.unidata.mdm.dq.core.service.impl.function.system.string;

import static org.unidata.mdm.dq.core.type.constant.CleanseConstants.INPUT_PORT_1;
import static org.unidata.mdm.dq.core.type.constant.CleanseConstants.INPUT_PORT_2;
import static org.unidata.mdm.dq.core.type.constant.CleanseConstants.OUTPUT_PORT_1;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.BooleanUtils;
import org.unidata.mdm.core.type.data.ArrayAttribute;
import org.unidata.mdm.core.type.data.Attribute;
import org.unidata.mdm.core.type.data.SingleValueAttribute;
import org.unidata.mdm.dq.core.context.CleanseFunctionContext;
import org.unidata.mdm.dq.core.dto.CleanseFunctionResult;
import org.unidata.mdm.dq.core.service.impl.function.system.AbstractSystemCleanseFunction;
import org.unidata.mdm.dq.core.type.cleanse.CleanseFunctionConfiguration;
import org.unidata.mdm.dq.core.type.cleanse.CleanseFunctionExecutionScope;
import org.unidata.mdm.dq.core.type.cleanse.CleanseFunctionInputParam;
import org.unidata.mdm.dq.core.type.cleanse.CleanseFunctionOutputParam;
import org.unidata.mdm.dq.core.type.cleanse.CleanseFunctionPortFilteringMode;
import org.unidata.mdm.dq.core.type.cleanse.CleanseFunctionPortInputType;
import org.unidata.mdm.dq.core.type.cleanse.CleanseFunctionPortValueType;
import org.unidata.mdm.dq.core.type.constant.CleanseConstants;
import org.unidata.mdm.system.util.TextUtils;

/**
 * Checks string length.
 * @author ilya.bykov
 */
public class CheckLength extends AbstractSystemCleanseFunction {
    /**
     * Display name code.
     */
    private static final String FUNCTION_DISPLAY_NAME = "app.dq.functions.system.string.check.length.display.name";
    /**
     * Description code.
     */
    private static final String FUNCTION_DESCRIPTION = "app.dq.functions.system.string.check.length.decsription";
    /**
     * IP1 name code.
     */
    private static final String INPUT_PORT_1_NAME = "app.dq.functions.system.string.check.length.input.port1.name";
    /**
     * IP1 description code.
     */
    private static final String INPUT_PORT_1_DESCRIPTION = "app.dq.functions.system.string.check.length.input.port1.decsription";
    /**
     * IP2 name code.
     */
    private static final String INPUT_PORT_2_NAME = "app.dq.functions.system.string.check.length.input.port2.name";
    /**
     * IP2 description code.
     */
    private static final String INPUT_PORT_2_DESCRIPTION = "app.dq.functions.system.string.check.length.input.port2.decsription";
    /**
     * IP3 name code.
     */
    private static final String INPUT_PORT_3_NAME = "app.dq.functions.system.string.check.length.input.port3.name";
    /**
     * IP3 description code.
     */
    private static final String INPUT_PORT_3_DESCRIPTION = "app.dq.functions.system.string.check.length.input.port3.decsription";
    /**
     * OP1 name code.
     */
    private static final String OUTPUT_PORT_1_NAME = "app.dq.functions.system.string.check.length.output.port1.name";
    /**
     * OP1 description code.
     */
    private static final String OUTPUT_PORT_1_DESCRIPTION = "app.dq.functions.system.string.check.length.output.port1.decsription";
    /**
     * This function configuration.
     */
    private static final CleanseFunctionConfiguration CONFIGURATION
        = CleanseFunctionConfiguration.configuration()
            .supports(CleanseFunctionExecutionScope.GLOBAL, CleanseFunctionExecutionScope.LOCAL)
            .input(CleanseFunctionConfiguration.port()
                    .name(INPUT_PORT_1)
                    .displayName(() -> TextUtils.getText(INPUT_PORT_1_NAME))
                    .description(() -> TextUtils.getText(INPUT_PORT_1_DESCRIPTION))
                    .filteringMode(CleanseFunctionPortFilteringMode.MODE_ALL)
                    .inputTypes(CleanseFunctionPortInputType.SIMPLE, CleanseFunctionPortInputType.ARRAY)
                    .valueTypes(CleanseFunctionPortValueType.STRING)
                    .required(true)
                    .build())
            .input(CleanseFunctionConfiguration.port()
                    .name(INPUT_PORT_2)
                    .displayName(() -> TextUtils.getText(INPUT_PORT_2_NAME))
                    .description(() -> TextUtils.getText(INPUT_PORT_2_DESCRIPTION))
                    .filteringMode(CleanseFunctionPortFilteringMode.MODE_ALL)
                    .inputTypes(CleanseFunctionPortInputType.SIMPLE)
                    .valueTypes(CleanseFunctionPortValueType.INTEGER)
                    .required(false)
                    .build())
            .input(CleanseFunctionConfiguration.port()
                    .name(CleanseConstants.INPUT_PORT_3)
                    .displayName(() -> TextUtils.getText(INPUT_PORT_3_NAME))
                    .description(() -> TextUtils.getText(INPUT_PORT_3_DESCRIPTION))
                    .filteringMode(CleanseFunctionPortFilteringMode.MODE_ALL)
                    .inputTypes(CleanseFunctionPortInputType.SIMPLE)
                    .valueTypes(CleanseFunctionPortValueType.INTEGER)
                    .required(false)
                    .build())
            .output(CleanseFunctionConfiguration.port()
                    .name(OUTPUT_PORT_1)
                    .displayName(() -> TextUtils.getText(OUTPUT_PORT_1_NAME))
                    .description(() -> TextUtils.getText(OUTPUT_PORT_1_DESCRIPTION))
                    .filteringMode(CleanseFunctionPortFilteringMode.MODE_ALL)
                    .inputTypes(CleanseFunctionPortInputType.SIMPLE)
                    .valueTypes(CleanseFunctionPortValueType.BOOLEAN)
                    .required(true)
                    .build())
            .build();
    /**
     * Instantiates a new CF check value.
     */
    public CheckLength() {
        super("CheckLength", () -> TextUtils.getText(FUNCTION_DISPLAY_NAME), () -> TextUtils.getText(FUNCTION_DESCRIPTION));
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public CleanseFunctionConfiguration configure() {
        return CONFIGURATION;
    }
    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    public CleanseFunctionResult execute(CleanseFunctionContext ctx) {

        CleanseFunctionResult output = new CleanseFunctionResult();

        CleanseFunctionInputParam param1 = ctx.getInputParam(CleanseConstants.INPUT_PORT_1);
        CleanseFunctionInputParam param2 = ctx.getInputParam(CleanseConstants.INPUT_PORT_2);
        CleanseFunctionInputParam param3 = ctx.getInputParam(CleanseConstants.INPUT_PORT_3);

        Long minValue = param2 != null ? param2.toSingletonValue() : null;
        Long maxValue = param3 != null ? param3.toSingletonValue() : null;

        minValue = minValue == null || minValue == 0L ? Long.MIN_VALUE : minValue;
        maxValue = maxValue == null || maxValue == 0L ? Long.MAX_VALUE : maxValue;

        if (param1 == null || param1.isEmpty()) {
            output.putOutputParam(CleanseFunctionOutputParam.of(CleanseConstants.OUTPUT_PORT_1, Boolean.FALSE));
        } else {

            boolean[] result = new boolean[param1.getAttributes().size()];
            for (int i = 0; i < param1.getAttributes().size(); i++) {

                Attribute attribute = param1.getAttributes().get(i);
                List<String> valuesToCheck = attribute.isSingleValue()
                        ? Collections.singletonList(((SingleValueAttribute<String>) attribute).getValue())
                        : ((ArrayAttribute<String>) attribute).getValues();

                for (String valueToCheck : valuesToCheck) {

                    result[i] = Objects.isNull(valueToCheck)
                            || (valueToCheck.length() >= minValue)
                            && (valueToCheck.length() <= maxValue);

                    if (!result[i]) {
                        break;
                    }
                }

                if (!result[i]) {
                    output.addSpot(attribute.toLocalPath(), attribute);
                }
            }

            output.putOutputParam(CleanseFunctionOutputParam.of(CleanseConstants.OUTPUT_PORT_1, BooleanUtils.and(result)));
        }

        return output;
    }
}
